<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author LYS
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'proj:weekly:pmWeekly:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <!-- <template  #zcclSelect>
        <ListSelect
          selectType="materialSelect"
          :checkbox="true"
          :params="queryParams"
          :selectList="listSelectRef"
          @select="handSelect"
        />
      </template> -->

      <template #pmWeeklyMaterialList>
        <BasicTable
          @register="registerPmWeeklyMaterialTable"
          @row-click="handlePmWeeklyMaterialRowClick"
        />
        <a-button
          class="mt-2"
          @click="handlePmWeeklyMaterialAdd"
          v-auth="'proj:weekly:pmWeekly:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <ListSelect
      ref="xmzbxz"
      v-show="false"
      selectType="materialSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsProjWeeklyPmWeeklyForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { PmWeekly, pmWeeklySave, pmWeeklyForm } from '/@/api/proj/weekly/pmWeekly';
  import { officeTreeData } from '/@/api/sys/office';
  import { ListSelect } from '/@/components/ListSelect';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('proj.weekly.pmWeekly');
  const { showMessage } = useMessage();
  const record = ref<PmWeekly>({} as PmWeekly);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增周报') : t('编辑周报'),
  }));

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let xmzbxz = ref<any>('');

  let isShow = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },
    {
      label: t('项目名称'),
      field: 'projectname',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },
    // {
    //   label: t('填报时间'),
    //   field: 'createDate',
    //   component: 'DatePicker',
    //   componentProps: {
    //     format: 'YYYY-MM-DD HH:mm',
    //     showTime: { format: 'HH:mm' },
    //   },
    // },
    {
      label: t('开始日期'),
      field: 'starttime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
        disabled: computed(() => !isShow.value),
      },
    },

    {
      label: t('结束日期'),
      field: 'endtime',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
        disabled: computed(() => !isShow.value),
      },
    },
    {
      label: t('承包商'),
      field: 'contractor',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
    },
    {
      label: t('现场照片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmWeekly_image',
        uploadType: 'image',
        disabled: computed(() => !isShow.value),
      },
      colProps: { lg: 24, md: 24 },
      // 文件上传的必填验证实例
      // rules: [
      //   { required: true },
      //   {
      //     validator(_rule, value) {
      //       return new Promise((resolve, reject) => {
      //         const len = !value || value['testData_image__len'] || 0;
      //         if (len == 0) reject(t('请上传图片'));
      //         else resolve();
      //       });
      //     },
      //   },
      // ],
    },
    {
      label: t('施工内容'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 200,
        rows: 5,
        disabled: computed(() => !isShow.value),
      },
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: t('填报人'),
    //   field: 'createByName',
    //   component: 'TreeSelect',
    //   componentProps: {
    //     api: officeTreeData,
    //     params: { isLoadUser: true, userIdPrefix: '' },
    //     canSelectParent: false,
    //     allowClear: true,
    //   },
    // },
    // {
    //   label: t('材料明细'),
    //   field: 'zbclmx',
    //   component: 'Input',
    //   colProps: { lg: 24, md: 24 },
    //   slot: 'zcclSelect',
    //   show: false,
    // },

    {
      label: t('材料明细'),
      field: 'pmWeeklyMaterialList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'pmWeeklyMaterialList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerPmWeeklyMaterialTable, pmWeeklyMaterialTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmWeeklyMaterialDelete.bind(this, record),
          },
          auth: 'proj:weekly:pmWeekly:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmWeeklyMaterialTableData(_res: Recordable) {
    pmWeeklyMaterialTable.setColumns([
      {
        title: t('项目编号'),
        dataIndex: 'projectno',
        width: 130,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 50,
        // },
        // editRule: false,
      },
      {
        title: t('材料编号'),
        dataIndex: 'mcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('材料名称'),
        dataIndex: 'pmMaterial.mname',
        width: 130,
        align: 'left',
      },
      {
        title: t('消耗数量'),
        dataIndex: 'num',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: true,
      },
      {
        title: t('剩余数量'),
        dataIndex: 'syQty',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('单位'),
        dataIndex: 'unit',
        width: 80,
        align: 'left',
        // editRow: true,
        // editComponent: 'Input',
        // editComponentProps: {
        //   maxlength: 50,
        // },
        // editRule: false,
      },
    ]);
    pmWeeklyMaterialTable.setTableData(record.value.pmWeeklyMaterialList || []);
  }

  function handlePmWeeklyMaterialRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmWeeklyMaterialAdd() {
    // pmWeeklyMaterialTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    listSelectRef.value = [];
    // document.getElementById('form_item_zbclmx')?.click();
    xmzbxz.value.handleInputClick();
  }

  function handlePmWeeklyMaterialDelete(record: Recordable) {
    pmWeeklyMaterialTable.deleteTableDataRecord(record);
  }

  async function getPmWeeklyMaterialList() {
    let pmWeeklyMaterialListValid = true;
    let pmWeeklyMaterialList: Recordable[] = [];
    for (const record of pmWeeklyMaterialTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmWeeklyMaterialListValid = false;
      }
      pmWeeklyMaterialList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmWeeklyMaterialTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmWeeklyMaterialList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmWeeklyMaterialListValid) {
      throw { errorFields: [{ name: ['pmWeeklyMaterialList'] }] };
    }
    return pmWeeklyMaterialList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    queryParams.value = {};
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmWeeklyForm(data);

    record.value = (res.pmWeekly || {}) as PmWeekly;
    if (!data.id) {
      record.value.projectname = record.value.projInfo.projectname;
    }
    record.value.__t = new Date().getTime();
    queryParams.value = {
      pcode: record.value.projectno,
      bmain: 1,
    };
    setFieldsValue(record.value);
    setPmWeeklyMaterialTableData(res);
    setDrawerProps({ loading: false });
    isShow.value = hasPermission(['proj:weekly:pmWeekly:edit']);
  });
  async function handSelect(selectData) {
    let arr = await pmWeeklyMaterialTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.mcode == item.mcode) {
          flag = false;
        }
      });
      if (flag) {
        pmWeeklyMaterialTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          projectno: item.pcode,
          pmMaterial: {
            mname: item.mname,
          },
        });
      }
    });
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.pmWeeklyMaterialList = await getPmWeeklyMaterialList();
      // console.log('submit', params, data, record);
      const res = await pmWeeklySave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
